#!/usr/bin/env python
# -*- coding: utf-8 -*-

from fastapi import FastAPI, Request, Response
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

from routers.users import user_router
from routers.items import item_router
from models.database import Base, engine

"""
自定义FastApi应用中的元数据配置
    Title：在 OpenAPI 和自动 API 文档用户界面中作为 API 的标题/名称使用。
    Description：在 OpenAPI 和自动 API 文档用户界面中用作 API 的描述。
    Version：API 版本，例如 v2 或者 2.5.0。
"""


app = FastAPI(
    debug=True,
    title="这是测试Title",
    description="这是测试description",
    version="这是测试version"
)

app.include_router(user_router, prefix="/u", tags=["users"])
app.include_router(item_router, prefix="/i", tags=["items"])


def init_db():
    # 第一次运行时创建数据库表
    Base.metadata.create_all(bind=engine)
    print('完成创建数据库表...')

# 在应用启动时创建表
app.add_event_handler("startup", init_db)

# 应用终止时，如下
# app.add_event_handler('shutdown', func)



templates = Jinja2Templates(directory="./templates")
app.mount("/static", StaticFiles(directory="./static"), name="static")


@app.get("/")
def home(req: Request):
    return templates.TemplateResponse(
        "home.html",
        {
            "request": req
        }
    )



# FastAPI 学习之路（四十）后台任务
from fastapi import BackgroundTasks
import time


def write_big_text(email: str, msg: str = ""):
    time.sleep(10)
    with open("big_text.txt", mode="w") as email_file:
        content = f"name {email}: {msg}"
        email_file.write(content)


@app.post("/send_email")
async def send_email(email: str, background_task: BackgroundTasks):
    background_task.add_task(write_big_text, email, msg="啥都行")
    return {"message": "the task is running background"}


# FastAPI 学习之路（四十一）定制返回Response
@app.get("/legacy_with_header_cookie")
def legacy_with_header_cookie():
    headers = {"X-Xtoken": "LC-1", "Content-Language": "en-US"}
    data = """<?xml version="1.0"?>
            <shampoo>
            <Header>
                Apply shampoo here.
            </Header>
            <Body>
                You'll have to use soap here.
                HERE SOMETHING HEADER YOU DEFINED AND COOKIE
            </Body>
            </shampoo>
            """
    response = Response(content=data, media_type="application/xml", headers=headers)
    response.set_cookie(key="cookie_key_lc", value="mrli")
    return response


# 接口文档中隐藏接口
@app.get("/legacy", include_in_schema=False)
def get_legacy_data():
    data = """<?xml version="1.0"?>
        <shampoo>
        <Header>
            Apply shampoo here.
        </Header>
        <Body>
            You'll have to use soap here.
        </Body>
        </shampoo>
        """
    return Response(content=data, media_type="application/xml")


if __name__ == '__main__':
    import uvicorn
    uvicorn.run("main:app", host="127.0.0.1", port=8080, reload=True)